package com.huawei.struts.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.huawei.struts.util.PageBean;
import com.st.model.HtmlSelectOption;
import com.st.model.LjwPremissionT;
import com.st.model.LjwUserT;
import com.st.model.UserT;

/**
 * A data access object (DAO) providing persistence and search support for
 * LjwUserT entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.st.model.LjwUserT
 * @author MyEclipse Persistence Tools
 */

public class LjwUserTDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(LjwUserTDAO.class);
	// property constants
	public static final String USER_NAME = "userName";
	public static final String EMAIL = "email";
	public static final String USER_IMG = "userImg";
	public static final String PERSONAL_BACKGROUD_IMG = "personalBackgroudImg";
	public static final String USER_TYPE = "userType";
	public static final String BIRTH_DATE = "birthDate";
	public static final String USER_SIGNATURE = "userSignature";
	public static final String USER_INTEGRAL = "userIntegral";
	public static final String VILLAGE_ID = "villageId";

	protected void initDao() {
		// do nothing
	}

	public void save(LjwUserT transientInstance) {
		log.debug("saving LjwUserT instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(LjwUserT persistentInstance) {
		log.debug("deleting LjwUserT instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public LjwUserT findById(java.lang.Integer id) {
		log.debug("getting LjwUserT instance with id: " + id);
		try {
			LjwUserT instance = (LjwUserT) getHibernateTemplate().get(
					"com.st.model.LjwUserT", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(LjwUserT instance) {
		log.debug("finding LjwUserT instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding LjwUserT instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from LjwUserT as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUserName(final String userName) {
		
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				 
				String sql="SELECT ut.USER_ID userId,ut.USER_NAME userName,ut.EMAIL email," +
						"ut.USER_INTEGRAL userSignature,ut.USER_TYPE userType,rt.ROLE_ID roleId," +
						"rt.ROLE_NAME roleName,pt.PROGRAM_ID programId,pt.PROGRAM_NAME programName FROM " +
						"LJW_USER_T ut  LEFT JOIN  LJW_USER_ROLE_PROGRAM_T  urpt " +
						"ON  urpt.USER_ID=ut.USER_ID LEFT JOIN LJW_ROLE_T rt " +
						"ON rt.ROLE_ID=urpt.ROLE_ID LEFT JOIN LJW_PROGRAM_T pt " +
						"ON pt.PROGRAM_ID=urpt.PROGRAM_ID WHERE ut.USER_NAME=?";
				 Connection con = session.connection();      
                 PreparedStatement ps = con.prepareStatement(sql);    
                 ps.setString(1, userName.toString());
                 log.info(sql);
                 ResultSet rs = ps.executeQuery();  
                 List<LjwUserT> list = new ArrayList<LjwUserT>();
                 while(rs.next()){
                	 LjwUserT user=new LjwUserT();
                	 user.setUserId(rs.getInt("userId"));
                	 user.setUserName(rs.getString("userName"));
                	 user.setEmail(rs.getString("email"));
                	 user.setUserSignature(rs.getString("userSignature"));
                	 user.setUserType(rs.getInt("userType"));
                	 user.setRoleId(rs.getInt("roleId"));
                	 user.setRoleName(rs.getString("roleName"));
                	 user.setProgramId(rs.getInt("programId"));
                	 user.setProgramName(rs.getString("programName"));
                	 list.add(user);
                 }
                 rs.close();
                 ps.close();
                 con.close();
				return list;
			}
		});
		return list;
	}
	
	public int checkPermission(final int role,final String module,final String opertor){
		Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				 String sql="SELECT	COUNT(*) amount FROM LJW_ACLENTRY_T lat INNER JOIN LJW_PREMISSION_T lpt ON lat.PERMISSION_ID=lpt.PERMISSION_ID WHERE lat.ROLE_ID=? AND lpt.R_UID=? AND lpt.PR_UID=?";
				 Connection con = session.connection();      
                 PreparedStatement ps = con.prepareStatement(sql);
                 ps.setInt(1, role);
                 ps.setString(2, module);
                 ps.setString(3, opertor);
                 ResultSet rs = ps.executeQuery();
                 
                 int amount=0;
                 if(rs.next())
                	 amount=rs.getInt(1);
                 rs.close();
                 ps.close();
                 con.close();
				return  Integer.valueOf(amount);
			}
		});
		return Integer.parseInt(count.toString());
	}

	public List findByEmail(Object email) {
		return findByProperty(EMAIL, email);
	}

	public List findByUserImg(Object userImg) {
		return findByProperty(USER_IMG, userImg);
	}

	public List findByPersonalBackgroudImg(Object personalBackgroudImg) {
		return findByProperty(PERSONAL_BACKGROUD_IMG, personalBackgroudImg);
	}

	public List findByUserType(Object userType) {
		return findByProperty(USER_TYPE, userType);
	}

	public List findByBirthDate(Object birthDate) {
		return findByProperty(BIRTH_DATE, birthDate);
	}

	public List findByUserSignature(Object userSignature) {
		return findByProperty(USER_SIGNATURE, userSignature);
	}

	public List findByUserIntegral(Object userIntegral) {
		return findByProperty(USER_INTEGRAL, userIntegral);
	}

	public List findByVillageId(Object villageId) {
		return findByProperty(VILLAGE_ID, villageId);
	}

	public List findAll() {
		log.debug("finding all LjwUserT instances");
		try {
			String queryString = "from LjwUserT";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public LjwUserT merge(LjwUserT detachedInstance) {
		log.debug("merging LjwUserT instance");
		try {
			LjwUserT result = (LjwUserT) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(LjwUserT instance) {
		log.debug("attaching dirty LjwUserT instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public List queryForPage(final LjwUserT user,final PageBean pageBean) {
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("from LjwUserT u where 1=1");
				Query query=queryMap(hql,user,session);
				query.setFirstResult(pageBean.getFirstResult());
				query.setMaxResults(pageBean.getPageSize());
				List list = query.list();
				return list;
			}
		});
		return list;
	}
	
	public int getAllRowCount(final LjwUserT user) {
		Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("select count(*) from LjwUserT u where 1=1");
				Query query=queryMap(hql,user,session); 
				return  Integer.parseInt(query.iterate().next().toString());
			}
		});
		return Integer.parseInt(count.toString());
	}
	
	public  Query queryMap(final StringBuffer hql,final LjwUserT user,Session session)
	{
		Map map=new HashMap();
		if(user.getUserName()!=null && !"".equals(user.getUserName()))
		{
			map.put("name", "%"+user.getUserName()+"%");
		    hql.append(" and u.userName like :name");
		}
		if(user.getUserImg()!=null && !"".equals(user.getUserImg()))
		{
			map.put("nameImg", "%"+user.getUserImg()+"%");
		    hql.append(" and u.userImg like :nameImg");
		}
		
		if(user.getEmail()!=null && !"".equals(user.getEmail()))
		{
			map.put("email", "%"+user.getEmail()+"%");
		    hql.append(" and u.email like :email");
		}
		
		if(user.getUserSignature()!=null && !"".equals(user.getUserSignature()))
		{
			map.put("userSignature", "%"+user.getUserSignature()+"%");
		    hql.append(" and u.userSignature like :userSignature");
		}
		Query query = session.createQuery(hql.toString());
		
		Iterator it = map.keySet().iterator();

         while (it.hasNext()){

         Object key = it.next(); 

         query.setParameter(key.toString(), map.get(key)); 

         }
         return query;
	}

	public void attachClean(LjwUserT instance) {
		log.debug("attaching clean LjwUserT instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static LjwUserTDAO getFromApplicationContext(ApplicationContext ctx) {
		return (LjwUserTDAO) ctx.getBean("LjwUserTDAO");
	}
	
	public boolean login(final LjwUserT user) {
		Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("select count(*) from LjwUserT u where 1=1");
				Query query=loginQueryMap(hql,user,session); 
				return  Integer.parseInt(query.iterate().next().toString());
			}
		});
		return count>0?true:false;
	}
	
	public  Query loginQueryMap(final StringBuffer hql,final LjwUserT user,Session session)
	{
		Map map=new HashMap();
		if(user.getUserName()!=null)
		{
			map.put("sname", user.getUserName());
		    hql.append(" and u.userName =:sname");
		}
		if(user.getUserPwd()!=null)
		{
			map.put("spassword", user.getUserPwd());
		    hql.append(" and u.userPwd =:spassword");
		}
		Query query = session.createQuery(hql.toString());
		
		Iterator it = map.keySet().iterator();

         while (it.hasNext()){

         Object key = it.next(); 

         query.setParameter(key.toString(), map.get(key)); 

         }
         return query;
	}

}